﻿using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.ERPSystem.ProductionSystem
{
    /// <summary>
    /// 班次服务层
    /// </summary>
    public class ShiftService : ApplicationService, IShiftService
    {
        private readonly IRepository<ShiftModel, int> _shiftRepository;

        public ShiftService(IRepository<ShiftModel, int> shiftRepository)
        {
            _shiftRepository = shiftRepository;
        }

        /// <summary>
        /// 获取班次分页列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <returns></returns>
        public async Task<ShiftPageResultDTO> GetShiftPageListAsync(int page = 1, int limit = 10)
        {
            try
            {
                var query = await _shiftRepository.GetQueryableAsync();
                
                var totalCount = query.Count();
                var shifts = query
                    .OrderBy(s => s.Id)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                var shiftDtos = shifts.Select(s => new ShiftDTO
                {
                    Id = s.Id,
                    ShiftName = s.ShiftName,
                    StartTime = s.StartTime,
                    EndTime = s.EndTime
                }).ToList();

                return new ShiftPageResultDTO
                {
                    Code = 0,
                    Msg = "查询成功",
                    Count = totalCount,
                    Data = shiftDtos
                };
            }
            catch (Exception ex)
            {
                return new ShiftPageResultDTO
                {
                    Code = 1,
                    Msg = $"查询班次列表失败：{ex.Message}",
                    Count = 0,
                    Data = new List<ShiftDTO>()
                };
            }
        }

        /// <summary>
        /// 添加班次
        /// </summary>
        /// <param name="shiftCreateDto">班次信息</param>
        /// <returns></returns>
        public async Task<bool> AddShiftAsync(ShiftCreateDTO shiftCreateDto)
        {
            try
            {
                if (string.IsNullOrEmpty(shiftCreateDto.ShiftName))
                {
                    return false;
                }

                // 解析时间字符串为DateTime，使用固定日期1900-01-01
                var baseDate = new DateTime(1900, 1, 1);
                var startTime = ParseTimeString(shiftCreateDto.StartTime, baseDate);
                var endTime = ParseTimeString(shiftCreateDto.EndTime, baseDate);

                var shift = new ShiftModel
                {
                    ShiftName = shiftCreateDto.ShiftName,
                    StartTime = startTime,
                    EndTime = endTime
                };

                await _shiftRepository.InsertAsync(shift);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 根据ID获取班次详情
        /// </summary>
        /// <param name="id">班次ID</param>
        /// <returns></returns>
        public async Task<ShiftDTO> GetShiftByIdAsync(int id)
        {
            try
            {
                var shift = await _shiftRepository.GetAsync(id);
                if (shift == null)
                {
                    return null;
                }

                return new ShiftDTO
                {
                    Id = shift.Id,
                    ShiftName = shift.ShiftName,
                    StartTime = shift.StartTime,
                    EndTime = shift.EndTime
                };
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 更新班次
        /// </summary>
        /// <param name="shiftUpdateDto">班次信息</param>
        /// <returns></returns>
        public async Task<bool> UpdateShiftAsync(ShiftUpdateDTO shiftUpdateDto)
        {
            try
            {
                if (string.IsNullOrEmpty(shiftUpdateDto.ShiftName))
                {
                    return false;
                }

                var shift = await _shiftRepository.GetAsync(shiftUpdateDto.Id);
                if (shift == null)
                {
                    return false;
                }

                // 解析时间字符串为DateTime，使用固定日期1900-01-01
                var baseDate = new DateTime(1900, 1, 1);
                var startTime = ParseTimeString(shiftUpdateDto.StartTime, baseDate);
                var endTime = ParseTimeString(shiftUpdateDto.EndTime, baseDate);

                shift.ShiftName = shiftUpdateDto.ShiftName;
                shift.StartTime = startTime;
                shift.EndTime = endTime;

                await _shiftRepository.UpdateAsync(shift);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除班次
        /// </summary>
        /// <param name="id">班次ID</param>
        /// <returns></returns>
        public async Task<bool> DeleteShiftAsync(int id)
        {
            try
            {
                var shift = await _shiftRepository.GetAsync(id);
                if (shift == null)
                {
                    return false;
                }

                await _shiftRepository.DeleteAsync(shift);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 解析时间字符串为DateTime
        /// </summary>
        /// <param name="timeString">时间字符串，格式为HH:mm（如08:00）</param>
        /// <param name="baseDate">基准日期</param>
        /// <returns></returns>
        private DateTime ParseTimeString(string timeString, DateTime baseDate)
        {
            try
            {
                var timeParts = timeString.Split(':');
                if (timeParts.Length == 2)
                {
                    var hours = int.Parse(timeParts[0]);
                    var minutes = int.Parse(timeParts[1]);
                    return new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, hours, minutes, 0);
                }
                
                // 如果解析失败，返回基准日期
                return baseDate;
            }
            catch
            {
                // 如果解析失败，返回基准日期
                return baseDate;
            }
        }
    }
}
